package cn.enilu.flash.service.blindbox;

import cn.enilu.flash.bean.entity.blindbox.BlindBox;
import cn.enilu.flash.bean.entity.blindbox.BlindBoxGoods;
import cn.enilu.flash.bean.entity.blindbox.BlindBoxGoodsUser;
import cn.enilu.flash.bean.entity.shop.Goods;
import cn.enilu.flash.bean.entity.shop.Order;
import cn.enilu.flash.bean.enumeration.FlagEnum;
import cn.enilu.flash.convert.GiftConvert;
import cn.enilu.flash.dao.blindbox.BlindBoxGoodsRepository;
import cn.enilu.flash.dao.blindbox.BlindBoxGoodsUserRepository;
import cn.enilu.flash.dao.blindbox.BlindBoxRepository;
import cn.enilu.flash.dao.shop.GoodsRepository;
import cn.enilu.flash.dao.shop.OrderRepository;
import cn.enilu.flash.service.BaseService;
import cn.enilu.flash.utils.lottery.LotteryUtil;
import cn.enilu.flash.utils.lottery.entity.Gift;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author HYF
 * @ClassName BlindboxService
 * @date 2022年04月27日 5:08 下午
 */
@Service
public class BlindboxService extends BaseService<BlindBox, Long, BlindBoxRepository> {
    @Resource
    private BlindBoxRepository blindBoxRepository;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private BlindBoxGoodsRepository blindBoxGoodsRepository;
    @Resource
    private GoodsRepository goodsRepository;
    @Resource
    private BlindBoxGoodsUserRepository blindBoxGoodsUserRepository;

    /**
     * 盲盒抽奖
     *
     * @param idUser
     * @param orderSn
     * @return
     */
    public List<Goods> luckDraw(Long idUser, String orderSn) {
        Order order = orderRepository.findOrderByIdUserAndOrderSn(idUser,orderSn);
        if (ObjectUtil.isEmpty(order)){
            throw new RuntimeException("异常抽奖");
        }
        List<BlindBoxGoods> blindBoxGoods = blindBoxGoodsRepository.findBlindBoxGoodsByBlindBoxId(order.getBlindBoxId());
        List<Gift> giftList = GiftConvert.INSTANCE.convertGift(blindBoxGoods);
        List<Gift> giftRet = LotteryUtil.getRangeGift(giftList,order.getTimes());
        List<Goods> ret = new ArrayList<>();
        for (Gift gift : giftRet) {
            Optional<Goods> goods =  goodsRepository.findById(gift.getGoodsId());
            BlindBoxGoodsUser blindboxGoodsUser = new BlindBoxGoodsUser();
            blindboxGoodsUser.setGoodsId(goods.get().getId());
            blindboxGoodsUser.setBlindBoxGoodsId(gift.getId());
            blindboxGoodsUser.setUserId(idUser);
            blindboxGoodsUser.setAvailableFlag(FlagEnum.YES.getKey());
            blindBoxGoodsUserRepository.save(blindboxGoodsUser);
            ret.add(goods.get());
        }

        return ret;
    }
}